--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:38:27
--
-- MallModel

local MallVo = import(".MallVo")
local LotteryVo = import(".LotteryVo")
local LotteryInfo = import(".LotteryInfo")
local PayVo = import(".PayVo")
local ShopDrawVo = import(".ShopDrawVo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

local CHECK_MIDAS_INTERVAL = 300

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()
	self._mallDatas = nil
	self._mallNews = {false, false, false, false, false, false}
	self._mallNewCronDict = {}
	self._version = nil

	self._lotteryInfos = nil
	self._isLotteryNew = false
	self._lotteryCron = nil
	self._drawState = false -- 是否进行了抽奖

	self._payDatas = nil -- 充值选项
	self._payGifts = nil -- 礼包直购
	self._payPrivilege = nil -- 特权礼包
	
	self._payMPInfoDict = nil -- msdk 给的充值运营信息

	self._payDataCache = nil -- 充值缓存

	self._giftPackages = nil

	self._shopDrawInfo = {} -- 翻牌抽奖系统信息

	self._lastCheckMidasTime = 0 -- 上次检测midas的时间

	local publisher = app:getInnerPublisher()
	if publisher == Enums.Publisher.tencent then
		self._shopIDs = Enums.TencentShopIds
		self._openServerShopId = 74002
	elseif publisher == Enums.Publisher.ema then
		self._shopIDs = Enums.EmaShopIds
		self._openServerShopId = 74001
	elseif publisher == Enums.Publisher.pwrd then
		self._shopIDs = Enums.PwrdShopIds
		self._openServerShopId = 74001
	else	-- default 防止报错
		self._shopIDs = Enums.TencentShopIds
		self._openServerShopId = 74002
	end
end

function ClassRef:initPayDatas(msg)
	self._payDatas = {}
	self._payGifts = {}
	self._payPrivilege = {}

	local payDatas = {}
	local payGifts = {}
	local payPrivilege = {}
	local confs = msg.RechargeGoodsInfos or {}
	for i,conf in ipairs(confs) do
		if conf.shopType == 1 or conf.shopType == 0 then
			payDatas[#payDatas + 1] = PayVo.new(conf)
		elseif conf.shopType == 2 then
			table.insert(payGifts, conf)
		elseif conf.shopType == 3 then
			table.insert(payPrivilege, conf)
		end
	end
	table.sort(payDatas, function(a, b)
		return a.id < b.id
	end)

	table.sort(payGifts, function(a, b)
		return a.ID < b.ID
	end)

	self._payGifts = payGifts
	self._payPrivilege = payPrivilege

	-- 充值需要整合平台获得的mpInfo
	if self._payMPInfoDict then
		for i,v in ipairs(payDatas) do
			local mpInfo = self._payMPInfoDict[v.diamond]
			v:initSDKData(mpInfo)
		end
	end
	self._payDatas = payDatas
end

-- 过滤商品 1.未达到等级的商品 2.一生限购买完的商品 3.限购时间到商品
function ClassRef:getMallDatas(shopIdx)
	local datas = self._mallDatas[self._shopIDs[shopIdx]] or {}
	local rets = {}
	local lv = UD:getLevel()
	local refreshGap = 65536
	local data, isOpen, gap
	local hasRemove = false
	for i=#datas,1,-1 do
		data = datas[i]
		if data:isLifeLimitOver() then
			-- 限购买完删除
			table.remove(datas, i)
			hasRemove = true
		elseif data:islvShow(lv) then
			isOpen, gap = data:checkOpen()
			if isOpen then
				rets[#rets + 1] = data
			end
			if gap then
				refreshGap = math.min(refreshGap, gap)
			elseif data:isTimeLimit() then
				-- 限购时间到删除
				table.remove(datas, i)
				hasRemove = true
			end
		end
	end

	if refreshGap == 65536 then
		refreshGap = nil
	end

	-- 有移除或者有定时道具，修改商店刷新new定时器
	if hasRemove or refreshGap ~= nil then
		self:refreshMallNew(shopIdx)
	end

	rets = table.DESC(rets)

	return rets, refreshGap
end

function ClassRef:getPayDatas()
	return self._payDatas
end

function ClassRef:getPayGifts()
	return self._payGifts
end

function ClassRef:getPayPrivilege()
	return self._payPrivilege
end

-- 商店new
function ClassRef:getMallNews()
	return self._mallNews
end

function ClassRef:getLotteryInfo(lotteryIdx)
	if self._lotteryInfos then
		return self._lotteryInfos[lotteryIdx]
	else
		return nil
	end
end

function ClassRef:refreshAllMallNew()
	for i=1,#self._shopIDs do
		self:refreshMallNew(i)
	end
end

-- 清除商店的new刷新定时器
function ClassRef:stopMallNewCron(shopIdx)
	if shopIdx then
		local cron = self._mallNewCronDict[shopIdx]
		scheduler.cancelCron(cron)
		self._mallNewCronDict[shopIdx] = nil
	else
		for i=1,#self._shopIDs do
			local cron = self._mallNewCronDict[i]
			scheduler.cancelCron(cron)
			self._mallNewCronDict[i] = nil
		end
	end
end

-- 刷新某一商店的new，并添加定时器
function ClassRef:refreshMallNew(shopIdx)
	local hasNew = false
	local refreshGap = 0
	local shopId = self._shopIDs[shopIdx]
	local datas = self._mallDatas[shopId] or {}
	local isNew, gap
	for _,data in ipairs(datas) do
		if data:isVisible() then
			isNew, gap = data:isNew()
			hasNew = hasNew or isNew
			if isNew then
				refreshGap = math.max(refreshGap, gap)
			end
		end
	end

	self._mallNews[shopIdx] = hasNew

	-- cancel possible cron
	self:stopMallNewCron(shopIdx)

	if refreshGap > 0 then
		self._mallNewCronDict[shopIdx] = scheduler.newCron(function()
			self._mallNewCronDict[shopIdx] = nil
			self._mallNews[shopIdx] = false
			app:sendMsg("MallController", "updateMallNew", shopIdx)
		end, refreshGap)
	end
end

function ClassRef:_refreshLotteryNew()
	self._isLotteryNew = false
	local refreshGap = 65536
	for i,info in ipairs(self._lotteryInfos) do
		local gap = info:getFreeTime()
		if gap <= 0 then
			self._isLotteryNew = true
			break
		else
			refreshGap = math.min(refreshGap, gap)
		end
	end

	UD.badge:setNum(Constant.FUNC_TYPE_SHOP, self._isLotteryNew and 1 or 0)
	UD.badge:setNum(Constant.FUNC_TYPE_LOTTERY, self._isLotteryNew and 1 or 0)
	
	if self._isLotteryNew then return end

	if self._lotteryCron then
		scheduler.cancelCron(self._lotteryCron)
		self._lotteryCron = nil
	end

	if refreshGap < 65536 then
		self._lotteryCron = scheduler.newCron(function()
			self._lotteryCron = nil
			self:_refreshLotteryNew()
		end, refreshGap)

		local date = os.date("*t", os.time())
		local time = date.hour*3600+ date.min*60 + date.sec + refreshGap
		app:sendMsg("PlayerController", "addPushNotice", 1001, time)
	end
end

--每天凌晨5点刷新次数
function ClassRef:onDailyUpdate(idx, shopIdx)
	if self._mallDatas then
		local changeDatas = {}
		for k,datas in pairs(self._mallDatas) do
			local isCur = (idx == 1) and (k == self._shopIDs[shopIdx])
			for _, data in ipairs(datas) do
				if data:isDayChange() then
					data:resetLeftNum()
					if isCur then
						changeDatas[#changeDatas + 1] = data
					end
				end
			end
		end

		if #changeDatas > 0 then
			app:sendMsg("MallController", "updateMall", changeDatas, shopIdx)
		end
	end
end

-- MSDK平台给的充值运营活动信息
function ClassRef:onPayMPInfoUpdate(mpInfo)
	if not mpInfo then return end
	local utp_mpinfo
	if mpInfo.mp_info then
		utp_mpinfo = mpInfo.mp_info.utp_mpinfo
	end

	if not utp_mpinfo then return end

	local payMPInfoDict = {}
	for i,v in ipairs(utp_mpinfo) do
		local num = tonumber(v.num)
		payMPInfoDict[num] = v
	end

	-- dump(payMPInfoDict, "payMPInfoDict")

	self._payMPInfoDict = payMPInfoDict

	if self._payDatas then
		-- 若在充值界面，需要刷新一下
		for i,v in ipairs(self._payDatas) do
			local mpInfo = self._payMPInfoDict[v.diamond]
			v:initSDKData(mpInfo)
		end

		app:sendMsg("MallController", "refreshPay")
	end
end

-- message ShopGoodsInfo{
--   int32 goodsId = 1; 
--   int32 svrLimitNowCount = 2;     //client 当前的数量
-- }
-- //需使用监听模式，全服抢购数量不变不回包
-- message S2C_QueryLimitGoods{
--   int32 shopId = 1;
--   repeated ShopGoodsInfo   retQuerys = 2;
-- }
function ClassRef:S2C_QueryLimitGoods(msg)
	if not self._mallDatas then return end
	-- dump(msg, "S2C_QueryLimitGoods", 10)

	local datas = self._mallDatas[msg.shopId]
	if not datas then return end

	local changeDatas = {}
	for _,data in ipairs(datas) do
		for _,info in ipairs(msg.retQuerys) do
			if info.goodsId == data.id then
				data:setRushNum(info.svrLimitNowCount)
				changeDatas[#changeDatas + 1] = data
				break
			end
		end
	end

	if #changeDatas > 0 then
		local shopIdx = table.indexof(self._shopIDs, msg.shopId)
		app:sendMsg("MallController", "updateMall", changeDatas, shopIdx)
	end
end

function ClassRef:setDrawState(state)
	self._drawState = state
end

function ClassRef:getDrawState()
	return self._drawState
end

function ClassRef:getShopDrawInfo()
	return self._shopDrawInfo
end

function ClassRef:getShopDrawInfoByIndex(idx)
	return self._shopDrawInfo[idx]
end

function ClassRef:getSelectedIdxById(id)
	local index = 1
	for i, v in ipairs(self._shopDrawInfo) do
		if v.info.id == id then
			index = i
			break
		end
	end
	return index
end

function ClassRef:getShopDrawMoneyInfo(index)
	local param = {}
	local info = self:getShopDrawInfoByIndex(index)
	if info then
		local conf = info.config
		local costs = string.split(conf.cost, "|")
		if tonumber(costs[1]) == Enums.lootType.item then -- 物品
			param.id = tonumber(costs[2])
			param.num = UD:getItemAmountByTid(param.id)
			param.type = Enums.TipsType.item
		else -- 货币
			param.id = tonumber(costs[1])
			param.num = UD:getDaibiValue( param.id )
			param.type = Enums.TipsType.daibi
		end 
	end
	return param
end

function ClassRef:showDrawIsOpen()
	return #self._shopDrawInfo > 0
end
-----------------------------------request------------------------------
function ClassRef:reqMallDatas(cb)
	if self._mallDatas then
		executeFunc(cb)
		return
	end

	app.session:request("pb_query.C2S_QueryShops", {shopIds=self._shopIDs}, function(msg)
		-- dump(msg, "pb_query.C2S_QueryShops", 10)
		local serverTime = app:getServerTime()
		self._mallDatas = {}
		for _,shop in ipairs(msg.shops) do
			local shopId = shop.shopId
			local datas = {}
			for i,v in ipairs(shop.goods) do
				-- 有限时时在限时结束之前
				if v.salesEndTime == 0 or v.salesEndTime > serverTime then
					datas[#datas + 1] = MallVo.new(v)
				end
			end
			self._mallDatas[shopId] = datas
		end
		self:refreshAllMallNew()
		executeFunc(cb)
	end, {block=true})
end

-- 拉取全服数量
function ClassRef:reqMallNum(shopIdx, rushParams)
	local params = {}
	params.shopId = self._shopIDs[shopIdx]
	params.querys = rushParams
	-- dump(rushParams, "C2S_QueryLimitGoods")
	app.session:request("pb_query.C2S_QueryLimitGoods", params)
end

function ClassRef:reqMallBuy(params, shopIdx)
	-- dump(params, "C2S_BuyGoods")
	app.session:request("action.C2S_BuyGoods", params, function(msg)
		-- dump(msg, "action.C2S_BuyGoods", 10)
		display.pushToast(L("tips_1080003"))

        local conf = GD:queryGoodById(params.goodsId)
        local nextGoodsID = conf.nextGoods or 0
		local goods = msg.goods
        local goodsId = goods.id
        local datas = self._mallDatas[self._shopIDs[shopIdx]] or {}
        if tonumber(nextGoodsID) == goodsId then
            --当前物品卖完了，刷新商品链下一个
            for k, v in ipairs(datas) do
                if v.id == params.goodsId then
                    table.remove(datas, k)
                    local lvData = MallVo.new(msg.goods)
                    table.insert(datas, k, lvData)
                    break
                end
            end
            app:sendMsg("MallController", "refreshMall", shopIdx)
        else
            for i,v in ipairs(datas) do
                if v.id == goods.id then
                    v:setLeftNum(goods.leftNum)
                    v:setRushNum(goods.svrLimitNowCount)
                    app:sendMsg("MallController", "updateMall", {v}, shopIdx)

                    -- 因为购买而一生限购买完了，自己还是new，需要刷新一下整个商店的new状态
                    local isNew = v:isNew()
                    if isNew and v:isLifeLimitOver() then
                        self:refreshMallNew(shopIdx)
                        app:sendMsg("MallController", "updateMallNew", shopIdx)
                    end
                    break
                end
            end
        end
	end, {block=true})
end

function ClassRef:reqBuyOpenServerGift(params)
	app.session:request("action.C2S_BuyGoods", params, function(msg)
		app:sendMsg("MallController", "updateOpenServerGifts", msg.goods, true)
	end)
end

function ClassRef:reqLotteryInfos()
	app.session:request("pb_activity.C2S_GetTenRandInfo", {quryActivityIdx=0},
		function(msg)
			-- dump(msg, "C2S_GetTenRandInfo", 10)
			self._lotteryInfos = {}
			self._isLotteryNew = false
			for i,v in ipairs(msg.infos) do
				self._lotteryInfos[i] = LotteryInfo.new(v)
			end
			self:_refreshLotteryNew()
		end)
end

function ClassRef:reqLottery(lotteryIdx, btnIdx)
	app:sendMsg("MallController", "setInLottery", true)

	-- for test
	-- local showLoots = {
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=77018201, num=1, type="mount"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- 	{dropLoot={id=71111212, num=1, type="item"}},
	-- }
	-- local datas = {}
	-- for i,v in ipairs(showLoots) do
	-- 	datas[i] = LotteryVo.new(v)
	-- end
	-- app:sendMsg("MallController", "openLotteryResultView", datas)
	-- do return end

	local param = {activityIdx=lotteryIdx, buttonIdx=btnIdx}
	-- dump(param, "MallModel.reqLottery")
	app.session:request("pb_activity.C2S_TenRandButton", param, function(msg)
		-- dump(msg, "C2S_TenRandButton", 10)
		local info = self._lotteryInfos[lotteryIdx]
		local nextRandInfo = msg.nextRandInfo
		info.nextGiftCount = nextRandInfo.nextGiftCount
		if info.nextFreeUnix ~= nextRandInfo.nextFreeUnix then
			-- 使用的免费次数
			info.nextFreeUnix = nextRandInfo.nextFreeUnix
			self:_refreshLotteryNew()
		end

		local datas = {}
		for i,v in ipairs(msg.showLoots) do
			datas[i] = LotteryVo.new(v)
		end
		app:sendMsg("MallController", "openLotteryResultView", datas)
		app:sendMsg("MallController", "updateLottery")
		self:setDrawState(true)
		app:sendMsg("RewardModel", "checkShowAdvert", Enums.ActivitySubType.Fund)
	end, {block=true}, function()
		app:sendMsg("MallController", "setInLottery", false)
	end)
end

-- 每次 进入 充值 界面  强制 拉取一次 商品列表
function ClassRef:reqPayDatas(isForce)
	-- 5秒 内 不重复请求
	if self._curReqPayDataTime then
		local nowTime = os.time()
		if nowTime - self._curReqPayDataTime < 5 then
			return 
		end
	end
	if self._payDatas and not isForce then 
		return 
	end

	self._curReqPayDataTime = os.time()
	app.channelAPI:getPayGoods(function(ret, msg)
		-- dump(msg, "getPayGoods---------->>>>")
		self:initPayDatas(msg)
		app:sendMsg("MallController", "refreshPay")
		app:sendMsg("MallController", "updateDailyGift", self:getPayGifts(), true)
	end)
end

-- 清理充值的第一次状态
function ClassRef:clearPayVoFirst(payVo)
	payVo:setIsFirst(false)
	if self._payMPInfoDict then
		local mpInfo = self._payMPInfoDict[payVo.diamond]
		if mpInfo then
			mpInfo.single_ex = nil
		end
	end
end

-- 当前是否在充值过程中
function ClassRef:isInPay()
	return self._payDataCache ~= nil
end

function ClassRef:reqPay(payData)
	-- dump(payData, "MallModel.reqPay")
	if not UD:isPayOpen() then
		display.pushToast(L("tips_1150013"))
		return
	end

	local function sdkPayCallback(ret)
		release_print("app.channelAPI:pay ret = " .. tostring(ret))
		self._payDataCache = nil
		if ret == Enums.PayRetState.success then
			if payData.shopType == 2 then	--海外每日礼包
			elseif payData.shopType == 3 then
--				display.pushToast("充值特权礼包成功。。。")
			else	-- 充值钻石
				if payData:isFirst() then
					self:clearPayVoFirst(payData)
					app:sendMsg("MallController", "updatePay", payData, Constant.FUNC_TYPE_RECHARGE)
				end
			end

			display.pushToast(L("demondShop_recharge_success"))
			self:reqCheckMidasPermission(true, handler(self, self.onCheckRecharge))
		else
			display.pushToast(L("demondShop_recharge_failure"))
		end
	end
	self._payDataCache = payData
	if app:getPublisher() == Enums.Publisher.ema then
		app.channelAPI:pay(sdkPayCallback, payData)
    elseif app:getPublisher() == Enums.Publisher.tencent then
		-- 通知服务器开始充值
		app.session:request("tencent.C2S_PreRecharge", {idx=payData.id})
		local params = {count = payData.diamond}
		if app:isIOS() then
			params.productId = payData.product_id
		end
		-- dump(params, "tencent.pay")
		app.channelAPI:pay(sdkPayCallback, params)
	elseif app:getPublisher() == Enums.Publisher.pwrd then
		-- 向服务器请求充值的订单ID和发放道具URL
		app.session:request("pb_recharge.C2S_StartRecharge", {}, function(msg)
			-- dump(msg, "S2C_StartRecharge------->>>>")
			local params = {
				productId = payData.product_id,
				orderID = msg.orderID,
				sendGoodsUrl = msg.sendGoodsUrl,
			}
			app.channelAPI:pay(sdkPayCallback, params)
		end)
	else
		app.session:request("tencent.C2S_PreRecharge", {idx=payData.id})
		app.channelAPI:pay(sdkPayCallback)
    end
end

function ClassRef:onCheckRecharge(msg)
	if msg.ok then
		-- 检查是否有充值缓存
		local payDataCache = self._payDataCache
		self._payDataCache = nil
		if payDataCache then
			if payDataCache.shopType == 2 then	--海外每日礼包
			elseif payDataCache.shopType == 3 then
				-- display.pushToast("充值特权礼包成功。。。")
			else	-- 充值钻石
				if payDataCache:isFirst() then
					app.channelAPI:getPayMPInfo()
				end
			end
		end
		-- 刷新累计充值活动
		app:sendMsg("RewardController", "refreshAccumulatedRecharge")
	else
		display.pushToast(L("demondShop_recharge_failure"))
	end
end

-- 检查midas平台权限，是否可以购买
function ClassRef:reqCheckMidasPermission(isForce, cb)
	if not app:isTencent() then return end

	-- 非强制检测有300s间隔
	local curTime = app:getTime()
	if not isForce and (curTime - self._lastCheckMidasTime) < CHECK_MIDAS_INTERVAL then
		return
	end

	self._lastCheckMidasTime = curTime
	local params = app.channelAPI:getMidasPermissionParams()
	app.session:request("tencent.C2S_CheckRecharge", params, function(msg)
		executeFunc(cb, msg)
	end)
end

function ClassRef:reqBuyGift(param)
    -- dump(param, "reqBuyGift")
    local giftID = param.giftID
    local conf = GD:getGiftBagInfoById(giftID)
    self:reqCheckMidasPermission()
    app.session:request("pb_activity.C2S_BuyGiftPackage", {giftID = giftID}, function(msg)
        -- dump(msg, "C2S_BuyGiftPackage")
        if msg.ok then
			local function sdkPayCallback(ret)
				if ret == Enums.PayRetState.success then
					display.pushToast(string.format(L("lua_code_text_370"), L(conf.name)))
					--self:reqRefreshGiftPackage()
				elseif ret == Enums.PayRetState.cancel then
					self:reqRefreshGiftPackage()
					display.pushToast(L("demondShop_recharge_failure"))
				else
					display.pushToast(L("demondShop_recharge_failure"))
	        	end
			end

			if app:getPublisher() == Enums.Publisher.ema then
				
			elseif app:getPublisher() == Enums.Publisher.tencent then
				local params = {}
				if app:isIOS() then
					params.count = table.concat({conf.product_id, conf.price, 1}, "*")
					params.isGameCoin = false
					params.productId = conf.product_id
				else
					params.count = 1
					params.goodsUrl = msg.chargeURL
				end
				-- dump(params, "tencent.pay")
				app.channelAPI:pay(sdkPayCallback, params)
			else
				app.channelAPI:pay(sdkPayCallback)
			end
        else
        	display.pushToast(L("lua_code_text_77"))
        end
    end)
end

-------------------------------------------------------------------------------
-- 是否还有未购买的腾讯超级礼包
function ClassRef:isHaveTencentSuperGift()
	if self._tencentSuperGifts then
		for i,v in ipairs(self._tencentSuperGifts) do
			if v.isCanBuy then
				return true
			end
		end
	end
	return false
end

-- tencent 每日礼包后两个商品
function ClassRef:S2C_GetGiftPackageInfo(msg)
	-- dump(msg, "S2C_GetGiftPackageInfo")

	local gifts = {}
	local superGifts = {}
	local gift, conf
	for i,v in ipairs(msg.gifts) do
		conf = GD:getGiftBagInfoById(v.giftID)
		if conf then
			gift = {}
			gift.giftID = v.giftID
			gift.isCanBuy = v.isCanBuy
			gift.conf = conf
			if conf.type == "1" then
				gifts[#gifts + 1] = gift
			elseif conf.type == "2" then
				superGifts[#superGifts + 1] = gift
			end
		end
	end

	table.sort(gifts, function(l, r)
	    return l.giftID < r.giftID
	end)
	table.sort(superGifts, function(l, r)
	    return l.giftID < r.giftID
	end)

	self._tencentGifts = gifts
	self._tencentSuperGifts = superGifts

    if self._reqGiftCB then
    	executeFunc(self._reqGiftCB)
    	self._reqGiftCB = nil
    end

	app:sendMsg("MallController", "updateGiftPackage", gifts, true)
	app:sendMsg("MallController", "updateSuperGiftPackage", superGifts, true)
end

function ClassRef:reqRefreshGiftPackage(cb)
	self._reqGiftCB = cb
    app.session:request("pb_activity.C2S_GetGiftPackageInfo", {})
end
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
-- 每日任务免费礼包（在tencent+ema都会有）
function ClassRef:reqGetGiftPackageInfo()
	app.session:request("pb_activity.C2S_GetProductPackageInfo", {})
end
--这条消息只发任务获得的礼包信息，另外两个礼包从其他消息获得
-- 1. ema 走充值消息过来(mallmodel:reqPayDatas())
-- 2. tencent 走C2S_GetGiftPackageInfo过来
function ClassRef:S2C_GetProductPackageInfo(msg)
	-- dump(msg, "S2C_GetProductPackageInfo")
	app:sendMsg("MallController", "updateDailyGift", msg, false)
	app:sendMsg("MallController", "updateGiftPackage", msg, false)
end

--做完任务获得礼包
function ClassRef:reqGetDailyGiftByTask()
	app.session:request("pb_activity.C2S_GetProductReward", {}, function()
        --服务器无返回，模拟服务器返回，刷新一次界面
        app:sendMsg("MallController", "updateDailyGift", {tasks = {[1] = {nowProgress = 3, needProgress = 3, isCanget = false}}}, false)
        app:sendMsg("MallController", "updateGiftPackage", {tasks = {[1] = {nowProgress = 3, needProgress = 3, isCanget = false}}}, false)
    end)
end
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
-- 开服礼包 （钻石购买礼包）
function ClassRef:reqOpenServerGifts(cb)
	app.session:request("pb_query.C2S_QueryShops", {shopIds={self._openServerShopId}}, function(msg)
		app:sendMsg("MallController", "updateOpenServerGifts", msg.shops, false)
		if cb then
			executeFunc(cb)
		end
	end)
end
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
-- 特权礼包（类似于月卡）（直购式礼包）
function ClassRef:reqPayPrivilege(data)
	local payData = self:getPayPrivilege()
	if payData and #payData > 0 then
		self:reqPay(payData[1])
	else
		release_print("特权礼包：reqPayPrivilege ====>> self:getPayPrivilege() is nil")
	end
end
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
--海外礼包购买反馈较慢，先通知ema服务器后再购买，防止错误下单
function ClassRef:reqEmaRecharge(param)
	-- dump(param)
	if param.shopType == 2 then	--每日礼包
		app:sendMsg("MallController", "updateDailyGiftEnabled", false)
	end
	app.session:request("pb_recharge.C2S_EmaCharge", {product_id = param.product_id}, function(msg)
		if msg.OK then
			if param.shopType == 2 then
				self:reqPay(param)
			elseif param.shopType == 3 then
				self:reqPayPrivilege(param)
			end
		end
	end)
end
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
function ClassRef:updatePayGoodsByEma(param)
	local gifts = self._payGifts
	if not gifts then return end
	local goodsList = param.RechargeGoodsInfos
	for _, v in ipairs(gifts) do
		for _, v2 in ipairs(goodsList) do
			if v.product_id == v2.product_id then
				v.num = v2.num
				break
			end
		end
	end

	app:sendMsg("MallController", "updateDailyGift", gifts, true)
end

----------------------------------------------------------------------------------
-- 翻牌抽奖系统
function ClassRef:reqGetShopDrawInfo(cb)
	app.session:request("pb_activity.C2S_GetShopDrawInfo", {}, function(msg)
		-- dump(msg.infos, "pb_activity.S2C_GetShopDrawInfo")
		self._shopDrawInfo = {}
		for i, v in ipairs(msg.infos) do
			local conf = GD:getShopDrawInfoById(v.id)
			if conf then
				table.insert(self._shopDrawInfo, {info = v, config = conf, order = tonumber(conf.orderIndex)})
			end
		end
		table.sort(self._shopDrawInfo, function(a, b)
			return a.order < b.order
		end)
		app:sendMsg("MallController", "refreshShopDraw")
		if cb then
			executeFunc(cb)
		end
	end)
end

function ClassRef:reqDrawCard(data)
	app:sendMsg("MallController", "setInShopDraw", true)
	app.session:request("pb_activity.C2S_DrawCard", data, function(msg)
		-- dump(msg, "pb_activity.S2C_DrawCard")
		for k, v in ipairs(self._shopDrawInfo) do
			if v.info.id == msg.nextInfos.id then
				self._shopDrawInfo[k].info = msg.nextInfos
			end
		end
		local datas = {}
		for i, v in ipairs(msg.showLoots) do
			datas[i] = ShopDrawVo.new(v, data.type)
		end
		app:sendMsg("MallController", "openShopDrawResultView", {resultInfo = data, lootData = datas})
		app:sendMsg("MallController", "refreshShopDrawView", data.id)
	end, {block=true}, function()
		app:sendMsg("MallController", "setInShopDraw", false)
	end)
end
----------------------------------------------------------------------------------

return ClassRef
